<!-- eslint-disable -->
<template>
  <el-form-item label="内容校验">
    <el-select v-model="props.formItem.rulesIndex" filterable>
      <el-option
        v-for="(item, index) in ruleList"
        :key="item.label"
        :label="item.label"
        :value="index"
      />
    </el-select>
  </el-form-item>
  <VAceEditor
    v-if="props.formItem.rulesIndex === ruleList.length - 1"
    v-model:value="rulesDetail"
    lang="javascript"
    theme="chrome"
    class="w-full h-60"
  />
</template>
<script setup lang="ts" name="FormRulesConfig">
import '@/utils/ace.config'
import { VAceEditor } from 'vue3-ace-editor'
import { ref, watch } from 'vue'
import {
  defaultRuleStr,
  isIdCardNumber,
  isNoEmpty,
  isPhoneNumber,
  isPositiveInteger,
  stringifyRules
} from '@/utils/rules'
const props = defineProps<{ formItem: SubmitFormSchema }>()
const ruleList = ref<{ label: string; value: string | null }[]>([
  { label: '无校验', value: null },
  {
    label: '必填项',
    value: stringifyRules(isNoEmpty)
  },
  {
    label: '必须是正整数',
    value: stringifyRules(isPositiveInteger)
  },
  {
    label: '必须是身份证号',
    value: stringifyRules(isIdCardNumber)
  },
  {
    label: '必须是手机号',
    value: stringifyRules(isPhoneNumber)
  },
  {
    label: '自定义校验',
    value: 'customRules'
  }
])
const rulesDetail = ref(defaultRuleStr)

const getCustomRule = () => {
  try {
    let customRules = {}
    eval(`customRules = ${rulesDetail.value}`)
    console.log(customRules)
    if (typeof customRules === 'object') {
      // eslint-disable-next-line
      props.formItem.rules = stringifyRules(customRules)
    }
  } catch (e) {
    console.log(e)
  }
}
// 监听自定义校验
watch(
  rulesDetail,
  (newVal, oldValue) => {
    if (newVal && oldValue) {
      getCustomRule()
    }
  },
  { immediate: true }
)
watch(
  () => props.formItem.rulesIndex,
  val => {
    if (val === ruleList.value.length - 1) {
      getCustomRule()
    } else if (typeof val === 'number') {
        props.formItem.rules = ruleList.value[val ?? 0]?.value // eslint-disable-line
    }
  },
  { immediate: true }
)
</script>
